package com.ddz.library.screen

import android.graphics.Bitmap
import android.graphics.Rect
import android.os.Handler
import android.os.Looper
import android.view.PixelCopy
import android.view.View
import android.view.Window

object JKSnapshotUtils {
    /**
     * 获取截图
     * @param window 如果是Activity则传递Activity的Window，如果是Dialog则传递Dialog的Window
     * @param result 因为是使用的View.post，所以在这里面可以保证View绘制完毕
     */
    fun snapshot(
        window: Window,
        view: View,
        result: (postView: View, snapshotBitmap: Bitmap?) -> Unit
    ) {
        var snapshotBitmap: Bitmap? = null
        try {
            view.post {
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    val location = IntArray(2)
                    view.getLocationInWindow(location)
                    snapshotBitmap =
                        Bitmap.createBitmap(view.measuredWidth, view.measuredHeight, Bitmap.Config.ARGB_8888)
                    PixelCopy.request(
                        window,
                        Rect(
                            location[0],
                            location[1],
                            location[0] + view.measuredWidth,
                            location[1] + view.measuredHeight
                        ),
                        snapshotBitmap!!,
                        { copyResult ->
                            result.invoke(view, snapshotBitmap)
                        },
                        Handler(Looper.getMainLooper())
                    )
                } else {
                    view.isDrawingCacheEnabled = true
                    view.buildDrawingCache()
                    val bitmap = view.drawingCache
                    snapshotBitmap = Bitmap.createBitmap(bitmap)
                    view.isDrawingCacheEnabled = false
                    view.destroyDrawingCache()
                    result.invoke(view, snapshotBitmap)
                }
            }
        } catch (e: Exception) {
            result.invoke(view, snapshotBitmap)
            e.printStackTrace()
        }
    }
}